package com.leetcode_mianshi_150;

class Trie {

    private boolean isEnd;
    private Trie[] next;


    public Trie() {
        next = new Trie[26];
        isEnd = false;
    }
    
    public void insert(String word) {
        Trie node = this;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);

            if (node.next[c - 'a'] == null) {
                node.next[c - 'a'] = new Trie();
            }

            node = node.next[c - 'a'];
        }

        node.isEnd = true;
    }
    
    public boolean search(String word) {
        Trie node = this;

        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (node.next[c - 'a'] == null) {
                return false;
            }

            node = node.next[c - 'a'];
        }

        return node.isEnd;
    }
    
    public boolean startsWith(String prefix) {
        Trie node = this;

        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if (node.next[c - 'a'] == null) {
                return false;
            }
            node = node.next[c - 'a'];
        }

        return true;
    }
}


class Main {
    public static void main(String[] args) {
        Trie trie = new Trie();
        trie.insert("apple");
        System.out.println(trie.search("apple"));
        System.out.println(trie.search("app"));
        System.out.println(trie.startsWith("app"));
        trie.insert("app");
        System.out.println(trie.search("app"));
    }
}